package com.etc.demo.controller;

import com.etc.demo.utils.JDBC;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//@RestController
//public class LoginController {
//
//
//    @GetMapping("login")
//    public User login(String username,String password) {
//        User user = new User();
//        user.setPassword("123456");
//        user.setUsername("wangccc");
//        return user;
//    }
//    @GetMapping("hello")
//            public String hello (){
//        return "hello";
/**
 * 用户登录控制器
 */
@RestController
public class LoginController {


    /**
     * 用户新增
     * @param username
     * @param password
     * @return
     */
    @GetMapping("login")
    public String userAdd(String username ,String password) throws SQLException {

        if (username == null || username.length() <= 0) {
            return "请输入用户名";
        }
        if (password == null || password.length() <= 0) {
            return "请输入密码";
        }
        Connection con = JDBC.getCon();
        PreparedStatement p = con.prepareStatement("select * from user where username= ?");
        p.setString(1, username);
        ResultSet resultSet = p.executeQuery();
        String password1 = "";
        while (resultSet.next()) {
            password1 = resultSet.getString("password");

        }
        if (password1.equals(password)) {
            return "1";
        } else {
            return "0";
        }
    }

    @GetMapping("add")
    public String userAdd(String username ,String password,String loginname) throws SQLException {

        if (username == null || username.length() <=0){
            return "请输入用户名";
        }
        if (password == null || password.length() <=0){
            return "请输入密码";
        }
        if (loginname == null || loginname.length() <=0){
            return "请输入名字";
        }

        //获取链接对象
        Connection con = JDBC.getCon();
        //获取执行器
        PreparedStatement p = con.prepareStatement("insert into user(username,password,loginname) value(?,?,?)");

        p.setString(1,username);
        p.setString(2,password);
        p.setString(3,loginname);

        int result = p.executeUpdate();

        if (result == 1){
            return "1";
        }else {

            return "0";
        }


    }
}
